import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap } from './router.config.js'
import * as dd from 'dingtalk-jsapi'
import { corpId } from '@/config'
import { getDingTalkToken, getDingUserInfo } from '@/api/user'
const whiteList = ['/login']
const originalPush = Router.prototype.push
var dingdingStatus = true
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

const createRouter = () =>
  new Router({
    // mode: 'history', // 如果你是 history模式 需要配置vue.config.js publicPath
    base: '/h5',
    // base: process.env.BASE_URL,
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRouterMap
  })

const router = createRouter()

export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

router.beforeEach((to, from, next) => {
  let isLogin = Boolean(localStorage.getItem('token'))
  console.log(localStorage.getItem('token'), to)
  if (isLogin) {
    dingdingStatus = true
    next()
  } else {
    if (dd.env.platform !== 'notInDingTalk' && dingdingStatus) {
      // 钉钉免密登录
      dd.ready(() => {
        // dd.ready参数为回调函数，在环境准备就绪时触发，jsapi的调用需要保证在该回调函数触发后调用，否则无效。
        dd.runtime.permission.requestAuthCode({
          corpId,
          onSuccess: ({ code }) => {
            getDingTalkToken().then(({ access_token }) => {
              getDingUserInfo({ code, access_token }).then(res => {
                console.log(res)
                localStorage.setItem('token', res.token)
                localStorage.setItem('userInfo', JSON.stringify(res.user))
                next('/')
              })
            })
            // code
          },
          onFail: () => {
            dingdingStatus = false
            next('/login')
          }
        })
      })
    } else {
      // 账号密码登录
      if (whiteList.includes(to.path)) {
        next()
      } else {
        next('/login')
      }
    }
  }
})

export default router
